package _interview150;

import _object.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * 106. 从中序与后序遍历序列构造二叉树
 */
public class No106 {
    private int[] postorder;
    private int postIndex, len;
    private Map<Integer, Integer> inorderMap;

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        this.postorder = postorder;
        len = inorder.length;
        postIndex = len - 1;
        inorderMap = new HashMap<>();
        for (int i = 0; i < len; i++) {
            inorderMap.put(inorder[i], i);
        }
        return dfs(0, len - 1);
    }

    private TreeNode dfs(int left, int right) {
        if (left > right || right >= len) return null;
        int nodeVal = postorder[postIndex--];
        TreeNode node = new TreeNode(nodeVal);
        node.right = dfs(inorderMap.get(nodeVal) + 1, right);
        node.left = dfs(left, inorderMap.get(nodeVal) - 1);
        return node;
    }
}
